import { _decorator, Component, instantiate, Layers, Node, resources, Sprite, SpriteAtlas, SpriteFrame } from 'cc';
const { ccclass, property } = _decorator;

/**
 * 卡牌控制类
 * 会被挂载到card预制体上
 * 实现触摸上升，和触摸事件通知
 */

@ccclass('ImgMgr')
export class ImgMgr extends Component {
    private static _inst: ImgMgr;
    public static get inst(): ImgMgr {
        if (this._inst == null) {
            this._inst = new ImgMgr();
        }
        return this._inst;
    }

    @property(SpriteAtlas)
    cardSpriteAtlas: SpriteAtlas = null;

    public pokerVal: number = 0 
    private cardBackFileName = "02";//牌背面-除前缀文件名称

    public init(pokerVal?: number): void {
        

        if(pokerVal >= 0){
            this.pokerVal = pokerVal;
            this.show();//显示牌
        }
    }

    protected start(): void {
        // console.log("this.cardSpriteAtlas: ", this.cardSpriteAtlas.getSpriteFrame('card_02'))
    }

    /**
     * 显示牌面
     * //(花色*100)+牌点数，方便带花色比较大小[Value/100=整除是花色,Value%100=取模是牌点数
     * 服务器直接返回 val = (suit*100)+牌点数
     */
    private show(): void {
        // console.log("cardCtrl.show()===============")
        const cardSprite = this.node.getComponent(Sprite);
        let spriteFrameKey = this.pokerVal > 0 ? this.pokerVal : this.cardBackFileName; // 默认显示背面
        
        cardSprite.spriteFrame = this.cardSpriteAtlas.getSpriteFrame('card_' + spriteFrameKey)
        // console.log("cardSprite.spriteFrame: ", cardSprite.spriteFrame)
    }

    /**
     * 
     * @param thatNode 
     * @param isBack =true: 默认显示背面, false: 显示正面
     * @returns 
     */
    public flipToFrontOrBack(thatNode: Node, isBack: boolean = true): Promise<void> {
        return new Promise<void>( () => {
            let sprite = thatNode.getComponent(Sprite)
            let spriteFrameKey = thatNode.getComponent(ImgMgr).pokerVal;

            if(!isBack && spriteFrameKey > 0){
                sprite.spriteFrame = this.cardSpriteAtlas.getSpriteFrame('card_' + spriteFrameKey);
            }else{
                sprite.spriteFrame = this.cardSpriteAtlas.getSpriteFrame('card_' + this.cardBackFileName);
            }
            thatNode.layer = Layers.Enum.UI_2D;
        });
    


        // const cardSprite = node.getComponent(Sprite)
        // cardSprite.spriteFrame = this.cardSpriteAtlas.getSpriteFrame("card_" + this.cardBackFileName);//拼接字符串成为牌的文件名
    }

}


